#include "A_Config.h"
class AppFileManager : public AppBase
{
private:
    void createList();
    void listDir();

public:
    AppFileManager()
    {
        name = "filemanager";
        title = "文件管理器";
        description = "用来管理TF卡中的文件";
        image = "\xEF\x81\xBC";
    }
    /* data */
    String cwd = "/";
    String currentFile = "";
    lv_obj_t *list_file = NULL;
    lv_obj_t *panel_file_info;
    lv_obj_t *lbl_file_info;
    lv_obj_t *btn_open;
    lv_obj_t *btn_refresh;
    lv_obj_t *btn_rename;
    lv_obj_t *btn_delete;
    lv_obj_t *btn_new_file;
    lv_obj_t *btn_new_folder;
    bool refreshReq = false;
    bool refreshFileOnlyReq = false;
    bool openfileReq = false;
    bool renamefileReq = false;
    bool deletefileReq = false;
    bool newfileReq = false;
    bool newfolderReq = false;
    /* methods */
    void setup();
    void loop();
    void destruct();
};

static AppFileManager app;

static void updateFileDesc()
{
    char buf[120];
    if (app.currentFile != "")
    {
        File f = SDCARD.open(app.cwd + app.currentFile, "r");
        if (f)
        {
            sprintf(buf, "文件名：%s\n文件大小：%d", app.currentFile.c_str(), f.size());
        }
        else
        {
            sprintf(buf, "文件名：%s\n文件大小：错误", app.currentFile.c_str());
            lv_toast("无法打开文件");
        }
        lv_obj_clear_flag(app.btn_open, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(app.btn_rename, LV_OBJ_FLAG_HIDDEN);
    }
    else
    {
        int count = lv_obj_get_child_cnt(app.list_file) - 1;
        if (app.cwd == "")
            ++count;
        sprintf(buf, "%d 个项目", count);
        lv_obj_add_flag(app.btn_open, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_flag(app.btn_rename, LV_OBJ_FLAG_HIDDEN);
    }
    lv_label_set_text(app.lbl_file_info, buf);
}

static void event_up_select(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *obj = lv_event_get_target(e);
    if (code == LV_EVENT_CLICKED)
    {
        char tmp[40] = {0};
        if (app.cwd != "/")
        {
            app.cwd = app.cwd.substring(0, app.cwd.lastIndexOf('/'));
            if (app.cwd == "")
                app.cwd = "/";
            app.currentFile = "";
            app.refreshReq = true;
        }
    }
}

static void event_file_select(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *obj = lv_event_get_target(e);
    if (code == LV_EVENT_CLICKED)
    {
        char tmp[40] = {0};
        app.currentFile = lv_list_get_btn_text(app.list_file, obj);
        app.refreshFileOnlyReq = true;
    }
}

static void event_folder_select(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *obj = lv_event_get_target(e);
    if (code == LV_EVENT_CLICKED)
    {
        app.cwd = app.cwd + String(lv_list_get_btn_text(app.list_file, obj));
        app.currentFile = "";
        app.refreshReq = true;
    }
}

void AppFileManager::createList()
{
    list_file = lv_list_create(scr);
    lv_obj_set_size(list_file, lv_pct(60), lv_pct(90));
    lv_obj_align(list_file, LV_ALIGN_BOTTOM_LEFT, 0, 0);
    lv_obj_add_flag(list_file, LV_OBJ_FLAG_SCROLL_MOMENTUM);
}

void AppFileManager::listDir()
{
    LOCKLV();
    if (lv_obj_is_valid(list_file))
        lv_obj_del(list_file);
    createList();
    if (cwd != "/")
    {
        lv_obj_t *btn = lv_list_add_btn(list_file, LV_SYMBOL_DIRECTORY, "..");
        lv_obj_set_style_text_font(btn, &lv_font_chinese_16, 0);
        lv_obj_add_event_cb(btn, event_up_select, LV_EVENT_CLICKED, NULL);
    }
    File root = SDCARD.open(cwd);
    if (!root)
    {
        lv_toast("无法打开文件夹");
        UNLOCKLV();
        return;
    }
    File file = root.openNextFile();
    while (file)
    {
        if (file.isDirectory() == false)
        {
            lv_obj_t *btn = lv_list_add_btn(list_file, LV_SYMBOL_FILE, file.path() + cwd.length());
            lv_obj_set_style_text_font(btn, &lv_font_chinese_16, 0);
            lv_obj_add_event_cb(btn, event_file_select, LV_EVENT_CLICKED, NULL);
        }
        else
        {
            lv_obj_t *btn = lv_list_add_btn(list_file, LV_SYMBOL_DIRECTORY, file.path() + cwd.length());
            lv_obj_set_style_text_font(btn, &lv_font_chinese_16, 0);
            lv_obj_add_event_cb(btn, event_folder_select, LV_EVENT_CLICKED, NULL);
        }
        file = root.openNextFile();
    }
    UNLOCKLV();
}

void AppFileManager::setup()
{
    panel_file_info = lv_obj_create(scr);
    lv_obj_set_size(panel_file_info, lv_pct(37), lv_pct(100));
    lv_obj_align(panel_file_info, LV_ALIGN_BOTTOM_RIGHT, 0, 0);
    lv_obj_set_style_pad_all(panel_file_info, 6, 0);
    lv_obj_set_flex_flow(panel_file_info, LV_FLEX_FLOW_COLUMN);

    lbl_file_info = label(panel_file_info, "", 0, 0, true);
    lv_label_set_long_mode(lbl_file_info, LV_LABEL_LONG_WRAP);
    lv_obj_set_size(lbl_file_info, lv_pct(100), LV_SIZE_CONTENT);
    lv_obj_set_style_text_align(lbl_file_info, LV_TEXT_ALIGN_CENTER, 0);

    btn_open = button(panel_file_info, "打开", 0, 0, &openfileReq);
    btn_refresh = button(panel_file_info, "刷新", 0, 0, &refreshReq);
    btn_rename = button(panel_file_info, "重命名", 0, 0, &renamefileReq);
    btn_delete = button(panel_file_info, "删除", 0, 0, &deletefileReq);
    btn_new_file = button(scr, LV_SYMBOL_FILE, 0, 2, &newfileReq);
    lv_obj_set_size(btn_new_file, lv_pct(25), lv_pct(8));
    btn_new_folder = button(scr, LV_SYMBOL_DIRECTORY, 96, 2, &newfolderReq);
    lv_obj_set_size(btn_new_folder, lv_pct(25), lv_pct(8));

    listDir();
    updateFileDesc();
}

void AppFileManager::loop()
{
    AppBase::loop();
    if (refreshReq)
    {
        refreshReq = false;
        listDir();
        updateFileDesc();
    }
    if(refreshFileOnlyReq)
    {
        refreshFileOnlyReq = false;
        updateFileDesc();
    }
    if (newfileReq)
    {
        String fn = msgbox_string("请输入文件名", false);
        fn.replace('/', '_');
        fn.replace('\\', '_');
        fn.replace('\n', '_');
        fn.replace('&', '_');
        if (cwd != "/")
        {
            fn = cwd + "/" + fn;
        }
        else
        {
            fn = cwd + fn;
        }
        if (SDCARD.exists(fn) == true)
        {
            lv_toast("文件已存在");
            newfileReq = false;
            return;
        }
        File f = SDCARD.open(fn, "w");
        if (!f)
        {
            msgbox(LV_SYMBOL_WARNING " 错误", "无法创建文件");
            newfileReq = false;
            return;
        }
        f.close();
        newfileReq = false;
        refreshReq = true;
    }
    if (newfolderReq)
    {
        String fn = msgbox_string("请输入文件夹名", false);
        fn.replace('/', '_');
        fn.replace('\\', '_');
        fn.replace('\n', '_');
        fn.replace('&', '_');
        if (cwd != "/")
        {
            fn = cwd + "/" + fn;
        }
        else
        {
            fn = cwd + fn;
        }
        if (SDCARD.mkdir(fn))
        {
            lv_toast("文件夹创建成功");
        }
        else
        {
            lv_toast("文件夹创建失败");
        }
        newfolderReq = false;
        refreshReq = true;
    }
    if (renamefileReq)
    {
        String fn = msgbox_string("请输入新文件名", false);
        fn.replace('/', '_');
        fn.replace('\\', '_');
        fn.replace('\n', '_');
        fn.replace('&', '_');
        if (cwd != "/")
        {
            fn = cwd + "/" + fn;
        }
        else
        {
            fn = cwd + fn;
        }
        if (SDCARD.rename(cwd + currentFile, fn))
        {
            lv_toast("文件重命名成功");
        }
        else
        {
            lv_toast("文件重命名失败");
        }
        renamefileReq = false;
        refreshReq = true;
    }
    if (openfileReq)
    {
        // 实际文件名cwd + currentFile;
        appManager.parameter = cwd + currentFile;
        appManager.showAppList();
        openfileReq = false;
    }
    if (deletefileReq)
    {
        if (msgbox_yn("是否删除？此操作不可恢复"))
        {
            if (currentFile != "")
            {
                if (SDCARD.remove(cwd + currentFile))
                {
                    lv_toast("文件删除成功");
                    currentFile = "";
                }
            }
            else
            {
                if (cwd == "/")
                {
                    lv_toast("不能删除根目录");
                }
                else
                {
                    if (SDCARD.rmdir(cwd))
                    {
                        lv_toast("文件夹删除成功");

                        cwd = cwd.substring(0, cwd.lastIndexOf('/'));
                        if (cwd == "")
                            cwd = "/";
                    }
                    else
                    {
                        lv_toast("删除失败");
                    }
                }
            }
            refreshReq = true;
        }
        deletefileReq = false;
    }
}
void AppFileManager::destruct()
{
    lv_obj_del(list_file);
    list_file = NULL;
}